using Godot;
using System;
using System.Collections.Generic;

public partial class One : Node2D
{
   [Export] CharacterBody2D one;
   [Export] StaticBody2D Area1;
   [Export] Label labels;
   [Export] CharacterBody2D two;
   [Export] Label Label;
   [Export] Timer Timer;
   [Export] public string[] boss;
   // 用于确保所有文字都显示一次的队列
   private List<string> bossQueue = new List<string>();
   private int currentBossIndex = 0;
   // 移动速度（像素/秒）
   [Export] float moveSpeed = 800f;
   [Export] int time = 2; // 倒计时时间（秒）
   // two的移动相关变量
   [Export] float twoSpeed = 300f;
   Vector2 twoDirection = Vector2.Zero;
   Random random = new Random();
   bool twoActive = false;
   
   // 在Area1内随机生成的半径（像素）
   [Export] float areaRadius = 120f;
   // two 的存活时长（秒），越大持续时间越长
   [Export] float twoLifetime = 100f;
   float twoAge = 0f;
   // 判定越界的额外边距（像素），越大飞更远才消失
   [Export] float outMargin = 300f;

   // one 与 two 的碰撞半径（像素）
   [Export] float oneTwoHitRadius = 24f;
   
   // 圆环移动相关参数
   [Export] float circleRadius = 300f; // 圆环半径改为300
   Vector2 circleCenter = Vector2.Zero; // 圆心位置
   bool circleMovement = true; // 是否启用圆环移动模式
   
   // 圆环可视化相关
   private Line2D circleLine;
   private bool showCircle = true;

   public override void _Ready()
   {
   
      // 设置默认圆环半径，如果未设置的话
      if (circleRadius <= 0)
         circleRadius = 100f;
      
      CollisionShape2D collisionOne = one.GetNode<CollisionShape2D>("CollisionShape2D");
      one.Visible = true;
      two.Visible = false;
      Area1.Visible = true;
      
      // 初始化倒计时
      InitializeCountdown();
      
      // 创建可视化圆环
      CreateCircleVisualization();
      
      // 初始化boss文字队列
      InitializeBossQueue();
      
      // 启动two的随机生成
      StartTwoSpawn();
      
      // two 为 CharacterBody2D：清空碰撞层/掩码，避免阻挡 one；命中用距离检测
      if (two != null)
      {
         two.CollisionLayer = 0;
         two.CollisionMask = 0;

         // 如果 two 下存在 Area2D 子节点 Hitbox，则用其进行非阻挡的物理重叠检测
         var hitbox = two.GetNodeOrNull<Area2D>("Hitbox")
                      ?? two.GetNodeOrNull<Area2D>("hitbox")
                      ?? two.GetNodeOrNull<Area2D>("Area2D");
         if (hitbox != null)
         {
            hitbox.Monitoring = true;
            hitbox.Monitorable = true;
            // Layer3 专用于 two 的命中盒；Mask 只检测 Layer1（one）
            hitbox.CollisionLayer = 1 << 2; // Layer 3
            hitbox.CollisionMask = 1 << 0;  // Detect Layer 1
            hitbox.BodyEntered += (Node2D body) => {
               if (body == one)
               {
                  RespawnTwo();
               }
            };
         }
      }

      // one 需要能检测到 Area1(Layer2) 与 Hitbox(Layer3)
      if (one != null)
      {
         one.CollisionMask |= (1 << 1) | (1 << 2); // add Layer2 & Layer3
      }
   }

   public override void _Process(double delta)
   {
      // 非物理更新：仅用于 two 的位移与计时
      twoMove((float)delta);
   }

   public override void _PhysicsProcess(double delta)
   {
      // 物理更新：one 使用 MoveAndSlide 与场景中的物理体发生碰撞
      oneMove((float)delta);
      // 若没有 Hitbox（Area2D）则退化为距离检测
      var hitbox = two != null ? two.GetNodeOrNull<Area2D>("Hitbox") : null;
      if (hitbox == null)
      {
         CheckOneHitsTwoDistance();
      }
      
      // 设置圆心为Area1的位置或屏幕中心
      circleCenter = Area1 != null ? Area1.GlobalPosition : GetViewport().GetVisibleRect().Size / 2;

      // 在物理更新的最后一步更新可视化，确保与移动逻辑完全同步
      UpdateCircleVisualization();
   }

   void oneMove(float delta)
   { 
      if (circleMovement)
      {
         // 圆环移动模式
         Vector2 directionToCenter = (one.GlobalPosition - circleCenter).Normalized();
         Vector2 tangentDirection = new Vector2(-directionToCenter.Y, directionToCenter.X);
         
         Vector2 inputDirection = Vector2.Zero;
         if (Input.IsActionPressed("you")) inputDirection += tangentDirection;
         if (Input.IsActionPressed("zuo")) inputDirection -= tangentDirection;
         if (Input.IsActionPressed("xia")) inputDirection += directionToCenter;
         if (Input.IsActionPressed("shang")) inputDirection -= directionToCenter;

         if (inputDirection.Length() > 0)
         {
            inputDirection = inputDirection.Normalized();
         }

         one.Velocity = inputDirection * moveSpeed;
         
         // 移动后调整位置使其保持在圆环上
         one.MoveAndSlide();
         
         // 将玩家位置约束到圆环上
         Vector2 toCenter = one.GlobalPosition - circleCenter;
         one.GlobalPosition = circleCenter + toCenter.Normalized() * circleRadius;
      }
      else
      {
         // 原来的自由移动模式
         Vector2 inputDirection = Vector2.Zero;
         if (Input.IsActionPressed("you")) inputDirection.X += 3.0f;
         if (Input.IsActionPressed("zuo")) inputDirection.X -= 3.0f;
         if (Input.IsActionPressed("xia")) inputDirection.Y += 3.0f;
         if (Input.IsActionPressed("shang")) inputDirection.Y -= 3.0f;

         if (inputDirection.Length() > 0)
         {
            inputDirection = inputDirection.Normalized();
         }

         one.Velocity = inputDirection * moveSpeed;
         one.MoveAndSlide();
      }
   }

   void twoMove(float delta)
   { 
      if (twoActive && two != null)
      {
         // 向当前方向移动
         Vector2 movement = twoDirection * twoSpeed * delta;
         two.Position += movement;
         twoAge += delta;
         
         // 存活到期或飞出很远后重置等待下一次生成
         if (twoAge >= twoLifetime || IsOutOfBounds(two.Position))
         {
            RespawnTwo();
         }
      }
   }

   // 基于距离的命中检测：one 接触 two 时让 two 消失（two 不参与物理阻挡）
   void CheckOneHitsTwoDistance()
   {
      if (!twoActive || two == null || one == null) return;
      float dist = (one.GlobalPosition - two.GlobalPosition).Length();
      if (dist <= oneTwoHitRadius)
      {
         RespawnTwo();
      }
   }
   
   void StartTwoSpawn()
   {
      // 每2-5秒随机生成一个two
      GetTree().CreateTimer((float)random.NextDouble() * 3f + 2f).Timeout += () => {
         if (!twoActive)
         {
            SpawnTwo();
         }
         StartTwoSpawn(); // 递归调用，持续生成
      };
   }
   
   void SpawnTwo()
   {
      if (Area1 != null && two != null)
      {
         // 在以 Area1 为中心的圆形区域内随机生成位置（均匀分布）
         float angle = (float)(random.NextDouble() * Mathf.Tau);
         float radius = Mathf.Sqrt((float)random.NextDouble()) * areaRadius; // sqrt 保证均匀
         Vector2 offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius;
         two.Position = Area1.GlobalPosition + offset;
         two.Visible = true;
      
         // 按顺序选择一条文本并显示在 labels 上
         if (labels != null && bossQueue.Count > 0)
         {
            labels.Text = bossQueue[currentBossIndex];
            currentBossIndex = (currentBossIndex + 1) % bossQueue.Count;
         }
         
         // 发射方向：从 Area1 朝外（由中心指向生成点的外向）
         twoDirection = (two.Position - Area1.GlobalPosition).Normalized();
         
         twoActive = true;
         twoAge = 0f;
      }
   }

   
   
   void RespawnTwo()
   {
      twoActive = false;
      two.Visible = false;
      if (labels != null)
      {
         labels.Text = "";
      }
   }
   
   bool IsOutOfBounds(Vector2 position)
   {
      // 检查是否超出屏幕边界（加入更大的边距）
      Vector2 screenSize = GetViewport().GetVisibleRect().Size;
      return position.X < -outMargin || position.X > screenSize.X + outMargin || 
             position.Y < -outMargin || position.Y > screenSize.Y + outMargin;
   }
   
   // 创建圆环可视化
   void CreateCircleVisualization()
   {
      if (!showCircle) return;
      
      circleLine = new Line2D();
      circleLine.Width = 3.0f;
      circleLine.DefaultColor = new Color(1.0f, 1.0f, 0.8f, 1.0f); // 黄色，带一些透明度
      circleLine.Closed = true; // 闭合路径
      circleLine.ZIndex = 10; // 提高Z索引确保可见
      circleLine.Name = "CircleVisualization";
      
      // 创建圆形点集
      int segments = 64; // 圆环细分段数
      Vector2[] points = new Vector2[segments];
      for (int i = 0; i < segments; i++)
      {
         float angle = (Mathf.Pi * 2 * i) / segments;
         points[i] = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * circleRadius;
      }
      circleLine.Points = points;
      
      AddChild(circleLine);
      circleLine.Owner = GetTree().EditedSceneRoot;
   }
   
   // 更新圆环位置
   void UpdateCircleVisualization()
   {
      // 确保圆环中心与游戏逻辑中的圆心一致
      if (circleLine != null && showCircle)
      {
         circleLine.GlobalPosition = circleCenter;
         circleLine.Visible = true;
         
         // 每帧重新计算点，确保正确显示
         if (circleLine.Points.Length > 0)
         {
            int segments = circleLine.Points.Length;
            Vector2[] points = new Vector2[segments];
            for (int i = 0; i < segments; i++)
            {
               float angle = (Mathf.Pi * 2 * i) / segments;
               points[i] = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * circleRadius;
            }
            circleLine.Points = points;
         }
      }
      else if (circleLine != null)
      {
         circleLine.Visible = false;
      }
   }
   
   // 初始化boss文字队列
   void InitializeBossQueue()
   {
      bossQueue.Clear();
      if (boss != null && boss.Length > 0)
      {
         // 将所有boss文字添加到队列中
         foreach (string text in boss)
         {
            if (!string.IsNullOrEmpty(text))
            {
               bossQueue.Add(text);
            }
         }
         // 打乱队列顺序，确保随机性
         for (int i = bossQueue.Count - 1; i > 0; i--)
         {
            int j = random.Next(i + 1);
            string temp = bossQueue[i];
            bossQueue[i] = bossQueue[j];
            bossQueue[j] = temp;
         }
      }
      currentBossIndex = 0;
   }
   
   // 初始化倒计时
   void InitializeCountdown()
   {
      if (Label != null)
      {
         Label.Text = time.ToString();
      }
      
      if (Timer != null)
      {
         Timer.WaitTime = 1.0; // 每秒触发一次
         Timer.Timeout += OnTimerTimeout;
         Timer.Start();
      }
   }
   
   // 定时器超时事件
   void OnTimerTimeout()
   {
      time--;
      
      if (Label != null)
      {
         Label.Text = time.ToString();
      }
      
      // 倒计时结束，跳转到game场景
      if (time <= 0)
      {
      
         GetTree().ChangeSceneToFile("res://assent/tscn/changese3.tscn");
      }
   }
}